<?php

namespace App\Http\Livewire;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class UserProfile extends Component
{
    public $user;
    public $editMode = false;
    public $skillAddMode = false;
    public $name;
    public $surname;
    public $about;
    public $middle_name;
    public $newSkillDescription;
    public $newSkillSkills;

    protected $rules = [
        'name' => "bail|alpha|max:50|nullable",
        'surname' => "bail|alpha|max:50|nullable",
        'middle_name' => "bail|alpha|max:50|nullable",
        'about' => "bail"
    ];

    public function mount($userName)
    {
        $user = User::where('user_name', $userName)->with('skills')->firstOrFail();

        $this->user = $user;

        $this->name = $user->profile->name;
        $this->surname = $user->profile->surname;
        $this->middle_name = $user->profile->middle_name;
        $this->about = $user->profile->about;

    }

    public function toggleEditMode()
    {
        $this->editMode = !$this->editMode;
    }

    public function saveProfile()
    {
        if (Auth::user()->cannot('update', $this->user->profile)) {
            return;
        }

        $validatedProfile = $this->validate();

        $this->user->profile->update([
            //'user_id' => $this->user->id,
            'name' => $validatedProfile['name'],
            'surname' => $validatedProfile['surname'],
            'middle_name' => $validatedProfile['middle_name'],
            'about' => $validatedProfile['about']
        ]);

        $this->editMode = false;
    }

    public function newSkillSave()
    {
        if (Auth::user()->cannot('update', $this->user->profile)) {
            return;
        }

        $this->user->skills()->create([
            'description' => $this->newSkillDescription,
            'skills'=> $this->newSkillSkills
        ]);

        $this->skillAddMode = false;

        $this->newSkillSkills =  $this->newSkillDescription = '';

        $this->user->load('skills');
    }

    public function toggleAddSkill()
    {
        $this->skillAddMode = !$this->skillAddMode;
    }

    public function render()
    {
        return view('livewire.user.user-profile');
    }
}
